import $ from 'jquery'

interface Ifancytree {
  filterNodes(tid: string, match: string): void,

  showOnline(tid: string): void,

  showAll(tid: string): void,

  selectAll(tid: string, state: boolean): void,

  expandAll(tid: string, state: boolean): void
}

class BfFancytree implements Ifancytree {
  filterNodes(tid = "#ftid", match = "") {
    let $el: any = $(tid);
    let $tree = $el.fancytree("getTree");
    if (!match) {
      // 清空筛选功能
      $tree.clearFilter();
      return;
    }
    $tree.filterNodes(function (node) {
      return new RegExp(match, "ig").test(node.data.filterValue || node.title);
    }, $tree.options.filter);
  }

  showOnline(tid: string = '#ftid') {
    let $el: any = $(tid);
    let tree = $el.fancytree("getRootNode");
    if (tree) {
      tree.visit((node) => {
        if (!node.isFolder()) {
          let key = node.key;
          // state 判断设备是否在线
          let state = true;
          if (state) {
            $(node.li).show();
          } else {
            $(node.li).hide();
          }
        }
      });
    }

  }

  showAll(tid: string = '#ftid') {
    let $el: any = $(tid);
    let tree = $el.fancytree("getRootNode");
    if (tree) {
      tree.visit((node) => {
        if (!node.isFolder()) {
          $(node.li).show();
        }
      });
    }
  }

  selectAll(tid: string = '#ftid', state: boolean = false) {
    let $el: any = $(tid);
    let tree = $el.fancytree("getRootNode");
    if (tree) {
      tree.visit((node) => {
        node.setSelected(state);
      });
    }
  }

  expandAll(tid: string = '#ftid', state: boolean = false) {
    let $el: any = $(tid);
    let tree = $el.fancytree("getRootNode");
    if (tree) {
      tree.visit((node) => {
        node.setExpanded(state);
      });
    }
  }
}

export default new BfFancytree();
